<?php
/*
Copyright (C) 2009 de Flotte Maxence

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
?>
<?php
/**
 * Genrerate ZzG
 */
class ZzGenCache {

/**
 * Genrerate a ZzG file
 * @param int $alpPuzzle If 0 it's the "reading" puzzle, else it's the writing puzzle
 * @param string $lang Language of the reader
 * @param int $lid The label id
 * @param string $pathLid The path lid. For exemple it will be 3-2-1, if the get parameter label were 4-3-2-1
 * @param string $genUrl The relative url (from index.php) of the cache to generate
 */
	static function gen($altPuzzle, $lang, $lid, $pathLid, $genUrl) {
		if(!file_exists('./ZzG/'.$lid))
			mkdir('./ZzG/'.$lid);
		
		$infoLabel = ZzGenCache::getInfo($lid);
		
		if($altPuzzle == 1) {
			$puzzleName  = 'write'.ucfirst($infoLabel['type']);
		}
		else {
			$puzzleName  = 'read'.ucfirst($infoLabel['type']);
		}
		$puzzle = new ZzPuzzle($puzzleName);
		
		if(empty($infoLabel['group']))
			$infoLabel['group'] = 0;
		if(empty($infoLabel['user']))
			$infoLabel['user'] = 0;

		$GLOBALS['label_user'] = $infoLabel['user'];
		$GLOBALS['label_group'] = $infoLabel['group'];
		$GLOBALS['label_id'] = $infoLabel['id'];
		$GLOBALS['label_name'] = $infoLabel['name'];
		$GLOBALS['label_type'] = $infoLabel['type'];
		$GLOBALS['label_dateC'] = $infoLabel['dateC'];
		$GLOBALS['label_dateU'] = $infoLabel['dateU'];
		$GLOBALS['label_userW'] = $infoLabel['userW'];
		$GLOBALS['label_groupW'] = $infoLabel['groupW'];
		$GLOBALS['label_otherW'] = $infoLabel['otherW'];
		$GLOBALS['label_userR'] = $infoLabel['userR'];
		$GLOBALS['label_groupR'] = $infoLabel['groupR'];
		$GLOBALS['label_otherR'] = $infoLabel['otherR'];
		$GLOBALS['isStatic'] = true;

		$globals =  '
//Liste des variables globales
	$GLOBALS[\'label_user\'] = '.strval($infoLabel['user']).';
	$GLOBALS[\'label_group\'] = '.strval($infoLabel['group']).';
	$GLOBALS[\'label_id\'] = '.$infoLabel['id'].';
	$GLOBALS[\'label_name\'] = \''.addSlashes($infoLabel['name']).'\';
	$GLOBALS[\'label_type\'] = \''.$infoLabel['type'].'\';
	$GLOBALS[\'label_dateC\'] = '.$infoLabel['dateC'].';
	$GLOBALS[\'label_dateU\'] = '.$infoLabel['dateU'].';
	$GLOBALS[\'label_userW\'] = '.$infoLabel['userW'].';
	$GLOBALS[\'label_groupW\'] = '.$infoLabel['groupW'].';
	$GLOBALS[\'label_otherW\'] = '.$infoLabel['otherW'].';
	$GLOBALS[\'label_userR\'] = '.$infoLabel['userR'].';
	$GLOBALS[\'label_groupR\'] = '.$infoLabel['groupR'].';
	$GLOBALS[\'label_otherR\'] = '.$infoLabel['otherR'].';
	$GLOBALS[\'isStatic\'] = false;

	
	if(!empty($_POST[\'tmpId\']))
		$GLOBALS[\'tmpId\'] = $_POST[\'tmpId\'];
	else {
		if(empty($_SESSION[\'tmpId\']))
			$_SESSION[\'tmpId\'] = 1;
		else
			$_SESSION[\'tmpId\']++;
		$GLOBALS[\'tmpId\'] = $_SESSION[\'tmpId\'];
	}';

		if($_GET['altPuZZle'] == 'true') {
		$verif = '
//On verifie que le label est accéssible en écriture
	if(!labelIsWritable()) {
		loadZzS(\'ErrorLimitedRight\');
		exit();
	}';
		}
		else {
		$verif = '
//On verifie que le label est accéssible en lecture
	if(!labelIsReadable()) {
		loadZzS(\'ErrorLimitedRight\');
		exit();
	}';
		}


		//Titre de la page
			//$labelName = $infoLabel['name'];
			$tr = new ZzTranslation('puZZleName',null);
			$title = addslashes($tr->tr($infoLabel['puZZleName'])).': '.addSlashes($infoLabel['name']);

		$return = '<?php
/*
	ZZG file
	Generate the '.date('d - m - Y').'
	By Puzzle Project '.$GLOBALS['version'].'
*/
//On vérifie l existance des sessions
	if(!isSet($_SESSION))
		exit();'.$globals.$verif.'
?>';

		
		ob_start();
			$puzzle->open();
			$gen = ob_get_contents();
		ob_end_clean();
		
		//Création des pièces dynamique
		$boutDeclaration = '
<?php //Create dynamics bouts';
		if(is_array($GLOBALS['bouts']))
			foreach($GLOBALS['bouts'] as $bout) {
				$boutDeclaration .= '
	$'.$bout['name'].' = new '.$bout['bootName'].'(\''.$bout['name'].'\',null);
'.$bout['autoset'].$bout['store'].'	$'.$bout['name'].'->buildBout();';
			}
		$boutDeclaration .= '
	//Destruction of all ZzIO instances
	if(is_array($GLOBALS[\'ioInstance\']))
	foreach($GLOBALS[\'ioInstance\'] as $instance) {
		$instance->__destruct();
	}
?>';

		file_put_contents($genUrl,$return.$boutDeclaration.$gen);
	}
/**
 * Get information (name, dateC, dateU, right, user, group, type) of a label
 * @param int $lid The label id
 * @return array Informations about the label
 */
	static function getInfo($lid) {
		//If creation label ({type})
		if(!is_numeric($lid)) {
			$infoLabel['type'] = str_replace(array('{','}'),'',strToLower($lid));
			$infoLabel['user'] = !empty($_SESSION['id'])?$_SESSION['id']:1;
			$infoLabel['group'] = 1;
			$infoLabel['id'] = 0;
			$infoLabel['name'] = '';
			$infoLabel['dateC'] = time();
			$infoLabel['dateU'] = time();
			$infoLabel['userW'] = 1;
			$infoLabel['groupW'] = 1;
			$infoLabel['otherW'] = 1;
			$infoLabel['userR'] = 1;
			$infoLabel['groupR'] = 1;
			$infoLabel['otherR'] = 1;
			//Identifiant temporaire ?
				if(empty($_SESSION['tmpId']))
					$_SESSION['tmpId'] = 1;
				else
					$_SESSION['tmpId']++;
				$GLOBALS['tmpId'] = $_SESSION['tmpId'];
		}
		//If normal lid
			else {
				//Get information from the store
					if($GLOBALS['store'] and file_exists('./ZzStore/'.$lid.'.php')) {
						$_res = unserialize(file_get_contents('./ZzStore/'.$lid.'.php'));
						$infoLabel['id'] = $lid;
						$infoLabel['name'] = $_res['name'];
						$infoLabel['type'] = $_res['type'];
						$infoLabel['dateC'] = $_res['dateC'];
						$infoLabel['dateU'] = $_res['dateU'];
						$infoLabel['user'] = $_res['user'];
						$infoLabel['group'] = $_res['group'];
						$infoLabel['userR'] = $_res['userR'];
						$infoLabel['userW'] = $_res['userW'];
						$infoLabel['groupR'] = $_res['groupR'];
						$infoLabel['groupW'] = $_res['groupW'];
						$infoLabel['otherR'] = $_res['otherR'];
						$infoLabel['otherW'] = $_res['otherW'];
					}
				//Get information from the database
					else {
						$infoLabel = ZzSQL::queryFirst('SELECT id, dateC, dateU, `type`, name, userR, userW, otherR, otherW, groupR, groupW, user, `group` FROM '.$GLOBALS['prefix'].'label  Where id=?',array($lid));
						if($GLOBALS['store'])
							file_put_contents('./ZzStore/'.$lid.'.php',serialize($infoLabel));
					}
			}
		return $infoLabel;
	}
}

?>